//
//  API.swift
//  SwiftRequest
//
//  Created by Pro on 2020/2/11.
//  Copyright © 2020 Pro. All rights reserved.
//

import Foundation
import Alamofire

enum HPHTTPMethod {
    case GET
    case POST
}

protocol HPRequest {
    var host : String {get}
    var path : String {get}
    var method : HPHTTPMethod {get}
    var parameter: [String: Any] { get }
    
    associatedtype Response
    func parse(data: NSDictionary) -> Response?
}

struct TencentRequest: HPRequest {
    typealias Response = RestanurantTotal
    var host: String  {
        return "https://apis.map.qq.com/ws/place/v1/"
//        ?region=北京&keyword=美食&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77
    }
    var path: String {
        return "suggestion/"
    }
    let method: HPHTTPMethod = .GET
    var parameter: [String : Any]
}

extension HPRequest {
    func sendRequest(hander:@escaping(Response?)->Void) {
        //...
        let url = self.host + self.path
        Alamofire.request(url, method: HTTPMethod.get, parameters: self.parameter).responseJSON { (response) in
                    switch response.result {
                    case .success(let data):
                           let dic = data as? NSDictionary
                           if let res = self.parse(data: dic!) {
                            hander(res)
                         }else {
                            hander(nil)
                         }
                        case .failure:
                            hander(nil)
                    }
                }
          }
}


extension TencentRequest {
    
    func parse(data: NSDictionary) -> RestanurantTotal? {
        return RestanurantTotal(data:data)
    }
}


